package com.xzxy.xmlg_backend.utils;

/**
 * @Author: zys
 * @CreateTime: 2025-06-13
 */


import jakarta.servlet.http.HttpServletRequest;

public class ServletUtil {

    /**
     * 获取客户端真实IP地址
     * 支持多级反向代理，如 Nginx + CDN 等场景
     */
    public static String getClientIP(HttpServletRequest request) {
        // 常用的获取客户端真实IP的请求头
        String[] headers = {
                "X-Forwarded-For",
                "Proxy-Client-IP",
                "WL-Proxy-Client-IP",
                "HTTP_CLIENT_IP",
                "HTTP_X_FORWARDED_FOR"
        };

        // 从请求头中获取IP
        for (String header : headers) {
            String ip = request.getHeader(header);
            if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
                // 多级代理时，第一个IP为真实客户端IP
                if (ip.contains(",")) {
                    return ip.split(",")[0].trim();
                }
                return ip;
            }
        }

        // 未从请求头获取到IP，使用远程地址
        return request.getRemoteAddr();
    }
}
